var http = require('http'),
  url = require('url'),
  fs = require('fs'),
  util = require('util');

http.createServer(function(req, res) {
  var pathname = url.parse(req.url).pathname;
  console.log('req.url:' + req.url); // /hello?a=123
  console.log('req.method:' + req.method); // get
  console.log('req.headers:' + util.inspect(req.headers));
  console.log(url.parse(req.url)); // Url对象:{search:'?a=123',query:'a=123',pathname:'/hello',path:'/hello?a=123'}
  console.log(pathname); // /hello
  switch (pathname) {
    case '/index':
      resIndex(res);
      break;
    case '/img':
      resImg(res);
      break;
    default:
      resDefault(res);
  }
}).listen(4000, '127.0.0.1');
console.log('server start at http://localhost:3000');

function resIndex(res) {
  var readPath = __dirname + '/views/' + url.parse('index.html').pathname;
  var indexPage = fs.readFileSync(readPath);
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end(indexPage);
}

function resImg(res) {
  var readPath = __dirname + '/static/imgs/' + url.parse('logo.png').pathname;
  var imgPage = fs.readFileSync(readPath);
  res.writeHead(200, { 'Content-Type': 'image/png' });
  res.end(imgPage);
}

function resDefault(res) {
  res.writeHead(404, { 'Content-Type': 'text/plain' });
  res.end('can not find Page!');
}
